package com.helpustotravel.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.helpustotravel.core.ServletBase;
import com.helpustotravel.model.dao.HelpDAO;
import com.helpustotravel.model.dao.PositionDAO;
import com.helpustotravel.model.dao.TravellerDAO;
import com.helpustotravel.model.jdo.Help;
import com.helpustotravel.model.jdo.Position;
import com.helpustotravel.model.jdo.Traveller;
import com.helpustotravel.utils.DateUtils;
import com.helpustotravel.utils.StringUtils;

@SuppressWarnings("serial")
public class GetAllTravellerInfosServlet extends ServletBase {
	
	public static String NAME = "GetAllTravellerInfos";
	
	protected HttpServletResponse doTache(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		TravellerDAO travellerDao = new TravellerDAO(pm);
		List<Traveller> travellers = travellerDao.getAllTraveller();
		
		String json = "{\"travellers\":[";
		
		for(int t = 0; t < travellers.size(); t++) {
			
			Traveller traveller = travellers.get(t);
		
			json += "{\"name\":\"" + traveller.getName() +
					"\",\"completeName\":\"" + traveller.getCompleteName() + 
					"\",\"type\":\"" + traveller.getType() + 
					"\",\"story\":\"" + StringUtils.escapeJavascript(traveller.getStory()) + 
					"\",\"positions\":[";
			
			List<Long> positions = traveller.getPositionIds();
			PositionDAO positionDao = new PositionDAO(pm);
			HelpDAO helpDao = new HelpDAO(pm);
			
			for(int i = 0; i < positions.size(); i++) {
				long id = positions.get(i);
				Position position = positionDao.getPosition(traveller.getName(), id);
				
				Help help = helpDao.getHelpByPosition(traveller.getName(), position.getId());
				if(help == null) {
					help = new Help();
				}
				
				if(position != null) {
					json += "{\"date\":\"" + DateUtils.formatDate(position.getDate()) + 
							"\",\"adresse\":\"" + position.getAdresse() +
							"\",\"x\":" + String.valueOf(position.getX()) + 
							",\"y\":" + String.valueOf(position.getY()) + 
							",\"level\":" + String.valueOf(position.getLevel()) + 
							",\"helpPrenom\":\"" + help.getPrenom() + 
							"\",\"helpComment\":\"" + StringUtils.escapeJavascript(help.getComment()) + 
							"\",\"helpEmail\":\"" + help.getEmail() + 
							"\",\"helpIp\":\"" + help.getIp() + 
							"\"}";
					
					if(i < (positions.size() - 1)) {
						json += ",";
					}
				}
			}
			
			json += "]}";

			if(t < (travellers.size() - 1)) {
				json += ",";
			}
		}
		
		json += "]}";
		
		resp.getWriter().print(json);
		return resp;
	}
}
